package org.windey.server;

import java.net.Socket;

import org.windey.Debug;
import org.windey.server.database.Database;
import org.windey.server.database.Md5Generator;
import org.windey.server.database.Pc;
import org.windey.server.database.User;

/**
 * 
 * 
 *
 */
public class ClientConnection extends WindeyConnection
{
	/**
	 * 
	 */
	private AppletConnection ac;
	private boolean authenticated;
	private Pc pc;
	
	/**
	 * 
	 * @param socket
	 */
	public ClientConnection(Socket socket)
	{
		super(socket);
		this.authenticated = false;
	}
	
	/**
	 * 
	 */
	public void run()
	{
		if (isRunning())
		{
			Debug.debug("clientconnection established (" + getSocket().getInetAddress().getHostAddress() + ")");
			if (!authenticated)
			{
				/*System.out.println("niet auth");
				String[] input = receive().split(";");
				Md5Generator gen = new Md5Generator();
				pc = new Pc();
				pc.setName(input[2]);
				User user = Database.getUser(input[0], input[1]);
				pc.setUser(user);

				pc.setOnline(true);
				pc = (Pc)Database.create(pc);
				System.out.println(pc);
				user.getPcs().add(pc);
				System.out.println("1: " + user.getPcs());
				user = (User)Database.edit(user);
				System.out.println("2: " + user.getPcs());
				this.setConnectionKey(gen.generateMD5(input[0]+";"+input[1]+";"+input[2]));
				authenticated = true;*/
				this.setConnectionKey(receive());
				this.authenticated = true;
			}
			if (authenticated)
			{
				System.out.println("auth");
				while (!getLinked())
				{
					try
					{
						ClientConnection.sleep(1000);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
				if (getLinked())
				{
					WindeyStreamThread wst = new WindeyStreamThread(this, ac);
					Debug.debug("appletconnection linked, stream started");
					send("WindeyStartStream");
					Debug.debug("wst started");
					wst.start();
				}
			}
			else
			{
				Debug.debug("no login");
			}
		}
	}

	/**
	 * 
	 * @param ac
	 */
	public void setAppletConnection(AppletConnection ac) {
		this.ac = ac;
		setLinked(true);
	}

	/**
	 * 
	 * @return
	 */
	public AppletConnection getAppletConnection() {
		return ac;
	}
	
	public void setOffline()
	{
		pc.setOnline(false);
	}
}
